class Order < ActiveRecord::Base
  has_many :order_details, :dependent => :destroy
  belongs_to :client

  attr_accessor :current_cart

  after_create :create_order_details, :queue #:send_email

  validate :has_items

  # Pagination settings
  self.per_page = configatron.pagination_my_orders_per_page

  def has_items
    if @current_cart.items.count == 0
      self.errors.add_to_base("El pedido debe contener al menos un producto.")
    end
  end

  def processed?
    self.status == 'processed'
  end

  def mark_as_processed
    unless self.status == 'processed'
      self.status = 'processed'
      self.processed_at = Time.now
      self.save(false)
    end
  end

  private

  def create_order_details
    @current_cart.items.each do |item|
      product = Product.find(item.product_id)

      od = OrderDetail.new(
        :order_id => self.id,
        :product_id => product.id,
        :product_color_id => item.color_id,
        :unit_price => product.get_price(@current_cart.kvn_branch),
        :quantity => item.quantity
      )

      od.save
    end
  end

  #def send_email
  #  # Notification for the company
  #  UserMailer.order_alert(self).deliver

    # Notification for the client
  #  UserMailer.order_received(self).deliver
  #end

  def queue
    OrderNotification.queque(self)
  end
end
